package 自定义数据库连接池;


import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.logging.Logger;

public class MyDataSource2 implements DataSource {
    private static ArrayList<Connection> list = new ArrayList<>();

    public MyDataSource2() {
        for (int i = 0; i < 10; i++) {
            Connection con = JDBCUtils.getConnection();
            Connection newProxyInstance = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("close".equals(method.getName())) {
                        System.out.println("addback");
                        //System.out.println("addback"+args.getClass());
                        list.add((Connection) proxy);

                        System.out.println("list.size():" + list.size());
                    } else {
                        System.out.println("methodName:" + method.getName());
                        return method.invoke(con, args);
                    }
                    return null;
                }
            });
            list.add(newProxyInstance);
        }
    }

    public void addBack(Connection con) {
        list.add(con);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return list.remove(0);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
